#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:sort_student_scores.py
# author:张世航
# datetime:2024/11/9 17:44
# software: PyCharm
"""
this is function  description 
"""
# import module your need

# 3 编写一个程序，读取文件中保存的10个学生成绩名单信息(学号,姓名, Python课程分数); 然后按照分数从高到低进行排序输出

import random

def create_student_scores_file(filename="scores.txt"):
    try:
        with open(filename, "w", encoding="utf-8") as file:
            for i in range(10):
                student_id = f"{random.randint(1000, 9999)}"  # 随机生成学号
                name = f"学生{i+1}"  # 学生姓名
                score = random.randint(60, 100)  # 随机生成分数（60-100）
                file.write(f"{student_id},{name},{score}\n")
        print(f"{filename} 文件已创建，包含随机学生成绩。")
    except Exception as e:
        print(f"发生错误: {e}")

create_student_scores_file()


def sort_student_scores(filename="scores.txt"):
    try:
        students = []
        with open(filename, "r", encoding="utf-8") as file:
            for line in file:
                student_info = line.strip().split(",")
                if len(student_info) == 3:
                    student_id, name, score = student_info
                    students.append((student_id, name, float(score)))

        # 按照分数从高到低排序
        students.sort(key=lambda x: x[2], reverse=True)

        print("学生成绩从高到低排序：")
        for student in students:
            print(f"学号: {student[0]}, 姓名: {student[1]}, 分数: {student[2]}")
    except FileNotFoundError:
        print("文件未找到。")
    except ValueError:
        print("分数格式错误。")
    except Exception as e:
        print(f"发生错误: {e}")

# 创建学生成绩文件
create_student_scores_file()

# 排序并输出学生成绩
sort_student_scores()